//
//  FunnyViewController.m
//  USB_Reader
//
//  Created by xiaozao on 15/3/21.
//  Copyright (c) 2015年 Tony_Wang. All rights reserved.
//

#import "FunnyViewController.h"
#import "AFNetworking.h"
#import "FunDataJSON.h"
#import "FunnyTableViewCell.h"
#import "FunDataHTTP.h"
#import "FunnyPhotoViewController.h"
#import "MBProgressHUD.h"
#import "Pull2RefreshTableView.h"

const NSInteger pull2RefreshHeaderHeight = 65;
const NSInteger pull2RefreshFooterHeight = 50;

@interface FunnyViewController () <UITableViewDataSource,UITableViewDelegate,MBProgressHUDDelegate>
@property (nonatomic, retain) UITableView *funTableView;
@property (nonatomic, retain) NSMutableArray *funArr;
@property (nonatomic, retain) FunDataJSON *funData;
@property (nonatomic, assign) NSInteger rowsNumber;
@property (nonatomic, retain) UISegmentedControl *funSeg;
@property (nonatomic, retain) MBProgressHUD *progress;

// 上拉下拉
@property (nonatomic, retain) Pull2RefreshTableView *pull2RefreshTableView;
@property (nonatomic, retain) NSMutableArray *dataSource;
@property (nonatomic, assign) BOOL reload;

@end

@implementation FunnyViewController

- (void)dealloc
{
    [_funTableView release];
    [_funArr release];
    [_funData release];
    [super dealloc];
}
- (void)hudWasHidden:(MBProgressHUD *)hud
{
    
    [_progress removeFromSuperview];
    [_progress release];
    _progress  = nil;
}

- (void)segDecide
{
    if (self.funSeg.selectedSegmentIndex == 1) {
        FunnyPhotoViewController *funnyPhotoVC = [[FunnyPhotoViewController alloc] init];
        [self.navigationController pushViewController:funnyPhotoVC animated:YES];
    }
    self.funSeg.selectedSegmentIndex = 0;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    

    // 添加导航栏中间标签
    self.funSeg = [[UISegmentedControl alloc] initWithItems:@[@"纯文",@"纯图"]];
    self.navigationItem.titleView = self.funSeg;
    [self.funSeg addTarget:self action:@selector(segDecide) forControlEvents:UIControlEventValueChanged];
    [_funSeg release];
    
    self.funTableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 0, self.view.frame.size.width - 20, self.view.frame.size.height) style:UITableViewStylePlain];
    _funTableView.dataSource = self;
    _funTableView.delegate = self;
    
    // 添加刷新
//    self.pull2RefreshTableView = [[Pull2RefreshTableView alloc] initWithFrame:self.view.bounds showDragRefreshHeader:YES showDragRefreshFooter:NO];
//    _pull2RefreshTableView.dragHeaderHeight = pull2RefreshHeaderHeight;
//    _pull2RefreshTableView.dragFooterHeight = pull2RefreshFooterHeight;
//    
//    __weak FunnyViewController *vc = self; // 注意错误
//    _pull2RefreshTableView.dragEndBlock = ^(Pull2RefreshViewType type)
//    {
//        if (type == kPull2RefreshViewTypeHeader)
//        {
//            [vc reloadInitDataInOtherThread];
//        }
//        else
//        {
//            [vc addMoreDataInOtherThread];
//        }
//    };
//    _pull2RefreshTableView.dataSource = self;
//    _pull2RefreshTableView.delegate = self;
//    [self.view addSubview:_pull2RefreshTableView];
    


    
//    _funTableView.backgroundColor = [[UIColor alloc] initWithRed:0.97254902 green:0.97254902 blue:0.97254902 alpha:1];
    self.view.backgroundColor = [[UIColor alloc] initWithRed:0.97254902 green:0.97254902 blue:0.97254902 alpha:1];
    [self.view addSubview:_funTableView];
    self.rowsNumber = 10;
    
    UISwipeGestureRecognizer * swipeLeftGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeGestureAction1:)];
    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    
    UISwipeGestureRecognizer * swipeRightGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeGestureAction1:)];
    swipeRightGesture.direction = UISwipeGestureRecognizerDirectionRight;
    

    [self.funTableView addGestureRecognizer:swipeLeftGesture];
    [self.funTableView addGestureRecognizer:swipeRightGesture];
    
//    // 异步分发任务
//    dispatch_queue_t global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_queue_t mainQueue = dispatch_get_main_queue();
//    dispatch_async(mainQueue, ^{
        self.progress = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [_progress show:YES];
        self.progress.delegate = self;
        self.progress.userInteractionEnabled = NO;

    
//    });
//    
//    dispatch_async(global, ^{
//        NSLog(@"在全局队列执行任务");
            [self dataAsk];

//    });
    

    [_funTableView release];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
}

// 添加滑动两个页面功能
- (void) swipeGestureAction1:(UISwipeGestureRecognizer *)recognizer {
    
    if (recognizer.direction==UISwipeGestureRecognizerDirectionLeft) {

         FunnyPhotoViewController *funnyPhotoVC = [[FunnyPhotoViewController alloc] init];
        [self.navigationController pushViewController:funnyPhotoVC animated:YES];
        NSLog(@"123");
    }
    else if (recognizer.direction == UISwipeGestureRecognizerDirectionRight){
//        FunnyPhotoViewController *funnyPhotoVC = [[FunnyPhotoViewController alloc] init];
//        //        funnyPhotoVC.view.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
//        [self.navigationController pushViewController:funnyPhotoVC animated:YES];
    }
}



- (void)dataAsk
{
    [FunDataHTTP requsetWithURL:@"http://m2.qiushibaike.com/article/list/text"  cache:@"cacheText"  completion:^(NSData *resultData) {
        id result = [NSJSONSerialization JSONObjectWithData:resultData options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *arr = [result objectForKey:@"items"];
        self.rowsNumber = arr.count;
        
        self.funArr = [NSMutableArray array];
        for (NSMutableDictionary *dic in arr) {
            FunDataJSON *data = [[FunDataJSON alloc] initWithDic:dic];
            [self.funArr addObject:data];
            [data release];
        }
        [_progress hide:YES];
        [self.funTableView reloadData];
    }];
}

//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
//    if (section < _rowsNumber)
//    {
//        return [[_funArr objectAtIndex:section] count];
//    }
//    
//    return 0;
//}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.rowsNumber;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"cell";
    FunnyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[FunnyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
    }
    cell.data =  [self.funArr objectAtIndex:indexPath.row];
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FunDataJSON *heighCount = [self.funArr objectAtIndex:indexPath.row];
    NSString *str = heighCount.content;
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
    CGRect rect = [str boundingRectWithSize:CGSizeMake(self.funTableView.frame.size.width, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}

// 刷新功能
- (void)addMoreDataInOtherThread
{
    [NSThread detachNewThreadSelector:@selector(addMoreData) toTarget:self withObject:nil];
}

- (void)addMoreData
{
    sleep(2);
    
    if (!_funArr)
    {
        _funArr = [NSMutableArray new];
    }
    
    NSArray *moreDataArr = [NSArray arrayWithObjects:@"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", nil];
    [_funArr addObject:moreDataArr];
    
    [_pull2RefreshTableView reloadData];
    [_pull2RefreshTableView completeDragRefresh];
    
    _pull2RefreshTableView.shouldShowDragFooter = YES;
    [_pull2RefreshTableView addDragFooterView];
}

- (void)reloadInitDataInOtherThread
{
    [NSThread detachNewThreadSelector:@selector(reloadInitData) toTarget:self withObject:nil];
}

- (void)reloadInitData
{
    sleep(20);
    if (_funArr.count > 0)
    {
        [_funArr removeAllObjects];
    }
    
    NSArray *initDataArr = [NSArray arrayWithObjects:@"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", @"Row", nil];
    [_funArr addObject:initDataArr];
    
    [_pull2RefreshTableView reloadData];
    [_pull2RefreshTableView completeDragRefresh];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
